/*
	Copyright (C) 2011 Simas Toleikis

	This file is part of Die2Nite Agent.

	Die2Nite Agent is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

"use strict";

var port = chrome.extension.connect();
var ignoreDOMChanges = false;

// Set external map status
function setMapStatus(status, message) {

	ignoreDOMChanges = true;

	var objectsHeader = $("#generic_section .right h2:first");
	var mapStatusElement = objectsHeader.find("#d2na-map-status");
	var statusMessage = null;

	// Add map update status icon
	if (!mapStatusElement.length) {

		mapStatusElement = $("<div/>");
		mapStatusElement.attr("id", "d2na-map-status");
		mapStatusElement.attr("onmouseout", "try { js.HordeTip.hide(); } catch(e) {}");
		mapStatusElement.css("backgroundImage", "url(" + chrome.extension.getURL("img/status.png") + ")");

		objectsHeader.append(mapStatusElement);
	}

	mapStatusElement.removeAttr("onmouseover");

	if (status == "disabled") {
		mapStatusElement.hide();
	}
	else if (mapStatusElement.is(":hidden")) {
		mapStatusElement.show();
	}

	// External map is up-to-date or in chaos mode
	if (status == "updated" || status == "chaos") {

		mapStatusElement.css({
			backgroundPosition: "0 0"
		});

		if (status == "chaos") {
			message = "You may not update external map while the town is in chaos mode or you are shunned!";
		}
	}
	// Update is in progress or pending
	else if (status == "updating") {

		mapStatusElement.css({
			backgroundPosition: "-12px 0"
		});
	}
	// Failed status (no keys available or communication issues)
	else if (status == "failed") {

		mapStatusElement.css({
			backgroundPosition: "-24px 0"
		});
	}

	if (message) {
		statusMessage = message;
	}

	if (statusMessage) {

		var onMouseOver = "try { js.HordeTip.showTip(this, 'External Map";

		var directoryIconURL = $("#sites h1 img").attr("src");
		if (directoryIconURL) {
			onMouseOver += ' <img src="' + directoryIconURL + '" />';
		}

		onMouseOver += "', '" + statusMessage + "'); } catch(e) {}";

		mapStatusElement.attr("onmouseover", onMouseOver);
	}

	// Update tooltip text if currently visible
	var tooltipMapStatus = $("#tooltip #d2na-map-status-text");
	if (tooltipMapStatus.length) {
		tooltipMapStatus.replaceWith(statusMessage);
	}

	ignoreDOMChanges = false;
}

// Update external maps
function updateMap() {

	var zoneState = {};

	// Outside items
	zoneState.outInv = "";
	$("#generic_section .right .outInv img").clone().each(function() {
		zoneState.outInv += this.outerHTML;
	});

	// Zone mark (nothing/items/depleted/etc)
	zoneState.zoneMark = $("#generic_section .right select.image option:selected").text();

	// Depleted zone status
	zoneState.depleted = $("#generic_section .left .driedZone").text();

	// Zombie control points
	zoneState.zombies = $("#zombiePts").text();

	// Human/player control points
	zoneState.humans = $("#humanPts").text();

	// Distance to town
	zoneState.scoutStatus = $("#scoutStatus").text();

	port.postMessage({type: "updateMap", zoneState: zoneState});
}

port.onMessage.addListener(function(msg) {

	// Update map status
	if (msg.type == "setMapStatus") {
		setMapStatus(msg.status, msg.message);
	}
});

// Detect chaos/shunned mode
$(".outside #generic_section .left").live("DOMNodeInserted", function() {

	var isChaosMode = false;
	if ($(this).find(".button img[src*=small_ban]").length) {
		isChaosMode = true;
	}

	port.postMessage({type: "setChaosMode", isChaosMode: isChaosMode});

	$(".outside #generic_section .left").die();
});

// Use DOM mutation events to track zone state changes
$(".outside #generic_section .right").live("DOMSubtreeModified DOMNodeInserted DOMNodeRemoved", function() {

	if (ignoreDOMChanges) {
		return;
	}

	updateMap();
});